package com.syt.cellphone.information.ui.main.phone.groups

import android.os.Bundle
import android.view.View
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.syt.cellphone.information.App
import com.syt.cellphone.information.R
import com.syt.cellphone.information.base.BaseFragment
import com.syt.cellphone.information.constant.EventBus
import com.syt.cellphone.information.data.pojo.BasePhoneList
import com.syt.cellphone.information.data.pojo.PhoneBase
import com.syt.cellphone.information.help.AppConfig
import com.syt.cellphone.information.lib.theme.ATH
import com.syt.cellphone.information.ui.main.MainViewModel
import com.syt.cellphone.information.ui.phone.details.PhoneDetailsActivity
import com.syt.cellphone.information.utils.getViewModelOfActivity
import com.syt.cellphone.information.utils.observeEvent
import kotlinx.android.synthetic.main.fragment_group_phone.*
import org.jetbrains.anko.startActivity

/**
 *  @author: syt
 *  创建时间: 2020/8/26 15:55
 *  @功能   分组手机数据
 *  @version v1.0
 */
class GroupPhoneFragment : BaseFragment(R.layout.fragment_group_phone) {

    companion object {
        fun newInstance(position: Int, groupId: Int): GroupPhoneFragment {
            return GroupPhoneFragment().apply {
                val bundle = Bundle()
                bundle.putInt("position", position)
                bundle.putInt("groupId", groupId)
                arguments = bundle
            }
        }
    }

    private val activityViewModel: MainViewModel
        get() = getViewModelOfActivity(MainViewModel::class.java)
    private lateinit var basePhoneAdapter: BasePhoneAdapter
    private var basePhoneLiveData: LiveData<List<PhoneBase>>? = null
    private var position = 0
    // -1 为最近更新 0 为全部数据
    private var groupId = -1

    override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
        arguments?.let {
            position = it.getInt("position", 0)
            groupId = it.getInt("groupId", -1)
        }
        // 加载数据
        initRecyclerView()
        // 更新数据
        upRecyclerData()
    }

    private fun initRecyclerView() {
        ATH.applyEdgeEffectColor(rv_group_phone)
        // 下拉刷新，暂时算全部刷新吧
        refresh_layout.setOnRefreshListener {
            it.finishRefresh(3000)
            activityViewModel.refreshPhoneBaseList()
        }
        // 上拉刷新
        refresh_layout.setOnLoadMoreListener {
            it.finishLoadMore(3000)
            activityViewModel.loadMorePhoneBaseList()
        }
        rv_group_phone.layoutManager = LinearLayoutManager(context)
        basePhoneAdapter = PhoneBaseAdapterList(requireContext(), object : BasePhoneAdapter.CallBack {
            override fun openPhoneInfo(base: PhoneBase) {
                // 打开详情Activity
                context?.startActivity<PhoneDetailsActivity>(Pair("phoneId", base.baseId.toString()))
            }
        })
        rv_group_phone.adapter = basePhoneAdapter
        basePhoneAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            // 插入范围计算
            override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                val layoutManager = rv_group_phone.layoutManager
                if (positionStart == 0 && layoutManager is LinearLayoutManager) {
                    // 计算滑动距离
                    val scrollTo = layoutManager.findFirstVisibleItemPosition() - itemCount
                    rv_group_phone.scrollToPosition(kotlin.math.max(0, scrollTo))
                }
            }
            // 移动范围
            override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
                val layoutManager = rv_group_phone.layoutManager
                if (toPosition == 0 && layoutManager is LinearLayoutManager) {
                    // 计算滑动距离
                    val scrollTo = layoutManager.findFirstVisibleItemPosition() - itemCount
                    rv_group_phone.scrollToPosition(kotlin.math.max(0, scrollTo))
                }
            }
        })
    }

    private fun upRecyclerData() {
        basePhoneLiveData?.removeObservers(this)
        basePhoneLiveData = when (groupId) {
            // todo 根据分组id来进行判断加载 暂时加载全部的
            else -> App.db.phoneBaseDao().observeAll()
        }
        // 数据处理 当数据发送改变时也会回调当前函数
        basePhoneLiveData?.observe(this, Observer {list ->
            // todo 暂时使用id排序 降序
            val basePhoneList = list.sortedByDescending { it.baseId }
            basePhoneAdapter.setItems(basePhoneList)
        })
    }

    override fun observeLiveBus() {
        super.observeLiveBus()
        observeEvent<BasePhoneList>(EventBus.UP_PHONE) {
            // 完成加载
            refresh_layout.finishLoadMore()
            refresh_layout.finishRefresh()
            // 重新查询数据
            basePhoneLiveData = App.db.phoneBaseDao().observeAll()
            // 更新数据
            basePhoneAdapter.notifyDataSetChanged()
        }
    }

    fun gotoTop() {
        if (AppConfig.isEInkMode) {
            rv_group_phone.scrollToPosition(0)
        } else {
            rv_group_phone.smoothScrollToPosition(0)
        }
    }
}